<?php
namespace app\user;

use app\repository\UserRepository;
use app\HeadComponent;
use app\alert\AlertComponent;
use app\service\TemplateService;

class UserComponent {
    public $extracts = [];

    public function __construct() {
        // 启用session，解决全局登录的问题
        session_start();

        if (!UserRepository::isLogin()) {
            header('Location: ./../login.view.php');
            die();
        }
    }

    public function add() {
        $this->assign('action', 'save.controller.php');
        return self::fetch('view/add.html');
    }

    /**
     * 模板传值
     * @param $key 关键字
     * @param $value 值
     * */
    private function assign($key, $value) {
        $this->extracts[$key] = $value;
    }

    /**
     * 
     * 编辑
     * 
     * */
    public function edit() {
        // 参数校验
        if (!isset($_GET['id'])) {
            echo '未传入ID';
            return;
        }

        // 获取要修改的用户
        $id = (int) $_GET['id'];
        $user = UserRepository::getById($id);
        $this->assign('user', $user);
        $httpReferer = $_SERVER['HTTP_REFERER'];
        $action = 'update.controller.php?id=' . $id;
        if (!is_null($httpReferer)) {
            $action .= '&referer=' . urlencode($httpReferer);
        }
        $this->assign('action', $action);

        return self::fetch('view/add.html');
    }

    /**
     * 
     * 渲染模板
     * 
     * */
    private function fetch($templateUrl) {
        return TemplateService::render($templateUrl, $this->extracts);
    }


    /**
     * 
     * 更新
     * 
     * */
    public function update() {
        // 参数校验
        if (!isset($_GET['id'])) {
            echo '未传入ID';
            return;
        }

        // 获取几个参数
        $id = (int) $_GET['id'];
        $name = $_POST['name'];
        $username = $_POST['username'];
        $role = $_POST['role'];

        // 去执行更新操作
        $status = UserRepository::updateById($id, $name, $username, $role);

        echo HeadComponent::render('更新用户');
        if ($status === true) {
            if (isset($_GET['referer'])) {
                $referer = $_GET['referer'];
            }
            
            $this->assign('scripts', AlertComponent::success(isset($referer) ? $referer : 'index.php', true));
            return $this->fetch('view/success.html');
        } else {
            $this->assign('scripts', AlertComponent::error($status));
            return $this->fetch('view/success.html');
        }
    }
}